package com.crm.web.admin;

import com.crm.entity.SysUser;
import com.crm.dto.UserLoginDto;
import com.crm.vo.UserLoginVo;
import com.crm.properties.JwtProperties;
import com.crm.result.Result;
import com.crm.service.SysLoginService;
import com.crm.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
/**
 * 登录
 */
@CrossOrigin
@RestController
class SysLoginController {
    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private JwtProperties jwtProperties;
    //用户登录
    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDto userLoginDto){
        SysUser sysUser  = sysLoginService.login(userLoginDto);
        //登录成功,验证令牌
        Map<String,Object> claims =new HashMap<>();
        claims.put("UserId",sysUser.getUserId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecret(),
                jwtProperties.getAdminTtl(),claims);
        UserLoginVo userLoginVo = UserLoginVo.builder()
                .userName(sysUser.getUserName())
                .userId(sysUser.getUserId())
                .token(token)
                .build();

        return Result.success(userLoginVo);
    }
}
